package me.ahy231.auth.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ahy231
 * @date 2021/6/27 21:19
 * @description
 */
@Slf4j
@Component
public class JwtUtils {

    // 用户id
    private static final String CLAIM_USER_ID = "USER_ID";
    // 创建时间
    private static final String CLAIM_KEY_CREATED = "CREATED";
    // 密钥
    private static final String SECRET = "LAWBU";
    // 过期时间
    private static final Long EXPIRATION = 1000 * 3600 * 24 * 3L;

    /**
     * 生成token
     * @param claims 声明
     * @return
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder().setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    /**
     * 根据openId生成Token
     * @param openId
     * @return
     */
    public String generateToken(Long openId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_USER_ID, openId);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    /**
     * 获取token负载
     * @param token
     * @return
     * @throws Exception
     */
    private Claims getClaimsFromToken(String token) throws Exception {
        return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
    }

    /**
     * 判断是否过期
     * @param token
     * @return
     * @throws Exception
     */
    public boolean isTokenExpired(String token) throws Exception {
        return getClaimsFromToken(token).getExpiration().before(new Date());
    }

    /**
     * 获取openId
     * @param token
     * @return
     * @throws Exception
     */
    public Long getOpenIdFromToken(String token) throws Exception {
        Long openId = getClaimsFromToken(token).get(CLAIM_USER_ID, Long.class);
        log.info("openId = {}", openId);
        return openId;
    }
}
